package chat;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MessageStorage {
    private static final String DATA_DIR = "chat_history/";

    static {
        File dir = new File(DATA_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    // 保存消息到文件
    public static void saveMessage(String username, String message) {
        String filePath = DATA_DIR + username + ".txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            writer.write(message);
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 加载用户的聊天记录
    public static List<String> loadMessages(String username) {
        List<String> messages = new ArrayList<>();
        String filePath = DATA_DIR + username + ".txt";
        File file = new File(filePath);
        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    messages.add(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return messages;
    }
}